/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, {Component} from 'react';
import {
    DeviceEventEmitter,
    FlatList,
    Image,
    Platform,
    UIManager,
    LayoutAnimation,
    RefreshControl,
    ScrollView,
    StyleSheet,
    Text,
    TouchableOpacity,
    View,
} from 'react-native';
import StyleUtils from "../../res/styles/StyleUtils";

import UserInformation from "./userInfo/UserInformation";
import BusinessPage from "./business/BusinessPage";
import OrdersPage from "./order/OrdersPage";
import AddressPage from "./address/AddressPage";
import WalletPage from "./walletAndWitdraw/WalletPage";
import DiscountCardsPage from "./discount/DiscountCardsPage";
import BankCardPage from "./bankCard/BankCardPage";
import BusinessPlanPage from "./business/BusinessPlanPage";
import SettingsPage from "./SettingsPage";
import SecurityPage from "./SecurityPage";
import VerifyPersonalPage from "./business/VerifyPersonalPage";
import CommonUtils from "../../common/CommonUtils";
import I18n from "../../res/language/i18n";
import CollectionPage from "../common/CollectionPage";
import IparNetwork, {IMAGE_URL, SERVER_TYPE} from "../../httpUtils/IparNetwork";
import PlansMainPage from "./business/PlansMainPage";
import ViewUtils from "../../utils/ViewUtils";
import IparImageView from "../../custom/IparImageView";
import ReturnOrdersPage from "../order/returnGoods/ReturnOrdersPage";
import ActivateOnePage from "../common/register/ActivateOnePage";


export default class MePage extends Component {

    constructor(props) {
        super(props);

        this.iparNetwork = new IparNetwork();


        this.state = {
            progressValue: 0,
            showLoading: false,
            showOperationView: false,
        };

    }


    /**
     * 网络请求
     * 获取用户详细信息
     */
    getUserInfo() {

        this.setState({
            showLoading: true,
        });

        let userInfo = this.props.userInfo;
        this.iparNetwork.getRequest(SERVER_TYPE.admin + 'getSubAccount?', 'user_id=' + userInfo.user_id)
            .then((result) => {
                this.setState({showLoading: false});
                if (result.code === 200) {
                    let userData = result.data;
                    DeviceEventEmitter.emit('upDateUserData', userData);
                }
                this.showOperation();
                console.log(result);
            })
            .catch((error) => {
                this.setState({showLoading: false});
                this.showOperation();
            })
    }

    componentDidMount() {

        this.deEmitterUserData = DeviceEventEmitter.addListener('loadUserData', () => {
            this.getUserInfo();
        });


        // this.timer = setTimeout(() => {
        //     this.showOperation();
        //     this.timer && clearTimeout(this.timer)
        // }, 200);


        this.getUserInfo();
    }

    /**
     * 打开操作提示器
     */
    showOperation() {
        this.startAnimation();
        this.setState({
            showOperationView: true,
        });
    }


    componentWillUnmount() {
        this.userUpdateDE && this.userUpdateDE.remove();
        this.deEmitterUserData && this.deEmitterUserData.remove();
    }


    /**
     *
     * @param type
     */
    onClickItems(type) {

        switch (type) {
            case 'myBusiness':
                this.props.navigator.push({
                    component: PlansMainPage,
                    params: {userId: this.props.userInfo.main_user_id}
                });
                break;
            case 'businessPlan':
                this.props.navigator.push({
                    component: BusinessPlanPage,
                    name: 'BusinessPlanPage',
                });
                break;
            case 'discountCards':
                this.props.navigator.push({component: DiscountCardsPage});
                break;
            case 'myOrders':
                this.props.navigator.push({component: OrdersPage});

                break;
            case 'returnOrderList':
                this.props.navigator.push({
                    component: ReturnOrdersPage,
                });

                break;
            case 'address':
                this.props.navigator.push({component: AddressPage});

                break;
            case 'bankCard':
                this.props.navigator.push({component: BankCardPage});

                break;
            case 'favourites':
                this.props.navigator.push({component: CollectionPage});

                break;
            // case 'verPersonal':
            //     this.props.navigator.push({component: VerifyPersonalPage});
            //
            //     break;
            case 'security':
                this.props.navigator.push({component: SecurityPage});

                break;
            case 'settings':
                this.props.navigator.push({component: SettingsPage});

                break;
            case 'wallet':
                this.props.navigator.push({component: WalletPage});
                break;
        }
    }

    /**
     *  init item
     *  @param item ({name:'',code:'',icon:...})
     */
    gitIparLabel(item) {
        return <TouchableOpacity
            activeOpacity={0.5}
            onPress={() => {
                this.onClickItems(item.code)
            }}
            style={[StyleUtils.listItem]}
        >
            <Image
                source={item.icon}
                style={{zIndex: 99, width: 18, height: 18, resizeMode: 'cover', tintColor: 'black'}}/>

            <Text style={[StyleUtils.smallFont, {
                fontSize: 16,
                flex: 1,
                color: 'black',
                textAlign: 'left',
                paddingLeft: 8,
            }]}>{item.name}</Text>
            <Image
                source={require('../../res/images/ic_right_more.png')}
                style={{width: 18, height: 18, resizeMode: 'cover'}}/>
        </TouchableOpacity>
    }


    /**
     * 动画效果
     */
    startAnimation() {
        if (Platform.OS === 'android') {
            UIManager.setLayoutAnimationEnabledExperimental(true);
        }
        LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut);
    }

    render() {
        /*my business */
        let myBusiness = false;
        let userInfo = this.props.userInfo;
        let progressSize = 0;

        if (userInfo) {
            if (userInfo.open_plan_num > 1 &&
                userInfo.is_contract === 1
            // userInfo.is_buy === 1 &&
            // userInfo.status === 4
            ) {
                myBusiness = true;
            }


            if (userInfo.open_plan_num > 1) {
                progressSize += 33;
            }
            if (userInfo.is_contract === 1) {
                progressSize += 33;
            }

            let isNotNull = userInfo && userInfo.first_name && userInfo.last_name && userInfo.id_number;

            if (isNotNull) {
                progressSize += 34;
            }
        }


        /**
         * label
         * */
            // let lableIcons = [
            //     {
            //         name: I18n.t('default.businessPlan'),
            //         code: 'businessPlan',
            //         icon: require('../../res/images/ic_business.png'),
            //     },
            //     {
            //         name: I18n.t('default.discountCards'),
            //         code: 'discountCards',
            //         icon: require('../../res/images/ic_discount.png'),
            //     },
            //     {
            //         name: I18n.t('default.myOrders'),
            //         code: 'myOrders',
            //         icon: require('../../res/images/ic_orders.png'),
            //     },
            //     {
            //         name: I18n.t('default.address'),
            //         code: 'address',
            //         icon: require('../../res/images/ic_address.png'),
            //     },
            //     {
            //         name: I18n.t('default.bankCard'),
            //         code: 'bankCard',
            //         icon: require('../../res/images/ic_bank_card.png'),
            //     },
            //     {
            //         name: I18n.t('default.favourites'),
            //         code: 'favourites',
            //         icon: require('../../res/images/ic_like.png'),
            //     },
            //     {
            //         name: I18n.t('default.verPersonal'),
            //         code: 'verPersonal',
            //         icon: require('../../res/images/ic_verify.png'),
            //     },
            //     {
            //         name: I18n.t('default.security'),
            //         code: 'security',
            //         icon: require('../../res/images/ic_security.png'),
            //     },
            //     {
            //         name: I18n.t('default.settings'),
            //         code: 'settings',
            //         icon: require('../../res/images/ic_settings.png'),
            //     },
            // ];


        let operationViewTitle = '';
        let operationViewUserData = null;
        let operationViewMsj = '';
        let operationViewType = null;
        // if (userInfo.status === 2) {
        //     operationViewType = 0;
        //     operationViewTitle = I18n.t('default.notVerified');
        //     operationViewMsj = I18n.t('default.haveInformationVerify');
        // }
        if (userInfo.status === 5) {
            operationViewType = 5;
            operationViewTitle = I18n.t('a.activateYourAccountTitle');
            operationViewMsj = I18n.t('a.activateYourAccountMsj');
        } else if (userInfo.open_plan_num <= 1) {
            operationViewType = 1;
            operationViewTitle = I18n.t('b.notSubsribed');
            operationViewMsj = I18n.t('b.registerIsIBMMinContent');
        } else {
            operationViewTitle = null;
            operationViewMsj = null;
            operationViewUserData = userInfo;
        }


        return (
            <ScrollView
                refreshControl={
                    <RefreshControl
                        refreshing={this.state.showLoading}
                        onRefresh={() => this.getUserInfo()}
                    />
                }
                style={{backgroundColor: 'white'}}>


                <View style={[styles.topBox, {padding: 16, paddingBottom: 0}]}>


                    <TouchableOpacity
                        style={[{
                            width: 70,
                            height: 70,
                            marginBottom: 20,

                        }, StyleUtils.center]}
                        onPress={() => {
                            this.props.navigator.push({
                                component: UserInformation,
                                name: 'UserInformation',
                                params: {
                                    userInfo,
                                }
                            })
                        }}
                    >


                        <IparImageView
                            errorImage={require('../../res/images/ic_avatar.png')}
                            borderRadius={35}
                            resizeMode={'cover'}
                            width={70}
                            height={70}
                            url={userInfo.head_img}/>


                    </TouchableOpacity>


                    <Text
                        numberOfLines={1}
                        style={[styles.userNameTv, StyleUtils.smallFont]}>{userInfo && userInfo.nick_name ? userInfo.nick_name : userInfo.user_name}</Text>
                    <Text
                        onPress={() => {
                            this.props.navigator.push({
                                component: UserInformation,
                                name: 'UserInformation',
                                params: {
                                    userInfo,
                                }
                            })
                        }}
                        numberOfLines={1}
                        style={[StyleUtils.smallFont, styles.checkDetailsTv, {marginBottom: 24}]}>{I18n.t('default.checkDetails')}</Text>

                    {ViewUtils.renderOperationView(operationViewUserData, operationViewUserData ? this : null, operationViewUserData ? null : () => {
                        if (operationViewType === 5) {
                            this.props.navigator.push({
                                component: ActivateOnePage,
                                params: {
                                    comeFromMePage: true,//来自
                                }
                            })
                        } else {
                            this.onClickItems('businessPlan');
                        }
                    }, operationViewTitle, operationViewMsj, this.state.showOperationView)}


                </View>


                <TouchableOpacity
                    activeOpacity={0.7}
                    onPress={() => {
                        this.props.navigator.push({component: BusinessPage})
                    }}
                    style={[styles.progressBox, StyleUtils.justifySpace]}>
                    <View style={[StyleUtils.rowDirection, {flex: 1}]}>
                        {/*<Text*/}
                        {/*    style={[StyleUtils.smallFont, {*/}
                        {/*        color: 'white',*/}
                        {/*        marginRight: 8,*/}
                        {/*        textAlign: 'left',*/}
                        {/*        backgroundColor: 'transparent'*/}
                        {/*    }]}>{I18n.t('default.identity')} :</Text>*/}

                        <Text
                            numberOfLines={1}
                            style={[StyleUtils.smallFont, {
                                textAlign: 'left',
                                color: 'white',
                                flex: 1,
                                backgroundColor: 'transparent'
                            }]}>{I18n.t('default.preRegistration')}</Text>
                    </View>

                    <Text style={{color: 'white'}}>{progressSize} %</Text>
                </TouchableOpacity>

                <View style={[StyleUtils.flex, {padding: 16}]}>


                    {/*<View style={StyleUtils.lineStyle}/>*/}


                    {this.gitIparLabel({
                        name: I18n.t('default.wallet'),
                        code: 'wallet',
                        icon: require('../../res/images/ic_wallet.png'),
                    },)}

                    {myBusiness ? this.gitIparLabel({
                        name: I18n.t('default.myBusiness'),
                        code: 'myBusiness',
                        icon: require('../../res/images/ic_my_business.png'),
                    }) : null}


                    {this.gitIparLabel({
                        name: I18n.t('default.businessPlan'),
                        code: 'businessPlan',
                        icon: require('../../res/images/ic_business.png'),
                    })}

                    {this.gitIparLabel({
                        name: I18n.t('default.discountCards'),
                        code: 'discountCards',
                        icon: require('../../res/images/ic_discount.png'),
                    })}
                    {this.gitIparLabel({
                        name: I18n.t('default.myOrders'),
                        code: 'myOrders',
                        icon: require('../../res/images/ic_orders.png'),
                    })}
                    {this.gitIparLabel({
                        name: I18n.t('RT.returnOrderList'),
                        code: 'returnOrderList',
                        icon: require('../../res/images/ic_return_goods.png'),
                    })}
                    {this.gitIparLabel({

                        name: I18n.t('default.address'),
                        code: 'address',
                        icon: require('../../res/images/ic_address.png'),
                    })}
                    {this.gitIparLabel({
                        name: I18n.t('default.bankCard'),
                        code: 'bankCard',
                        icon: require('../../res/images/ic_bank_card.png'),
                    })}
                    {this.gitIparLabel({
                        name: I18n.t('default.favourites'),
                        code: 'favourites',
                        icon: require('../../res/images/ic_like.png'),
                    })}
                    {/*{this.gitIparLabel({*/}
                    {/*name: I18n.t('default.verPersonal'),*/}
                    {/*code: 'verPersonal',*/}
                    {/*icon: require('../../res/images/ic_verify.png'),*/}
                    {/*})}*/}
                    {this.gitIparLabel({
                        name: I18n.t('default.security'),
                        code: 'security',
                        icon: require('../../res/images/ic_security.png'),
                    })}
                    {this.gitIparLabel({
                        name: I18n.t('default.settings'),
                        code: 'settings',
                        icon: require('../../res/images/ic_settings.png'),
                    })}
                    {/*<FlatList*/}
                    {/*data={lableIcons}*/}
                    {/*extraData={this.state}*/}
                    {/*renderItem={(item) => this.gitIparLabel(item.item)}/>*/}


                </View>


            </ScrollView>
        );
    }


}


const styles = StyleSheet.create({
    topBox: {
        backgroundColor: 'white',
        flexDirection: 'column',
        justifyContent: 'center',
        alignItems: 'center',
    },
    progressBox: {
        width: '100%',
        height: 60,
        backgroundColor: '#333',
        // marginTop: 70,
        paddingLeft: 20,
        paddingRight: 20,
    },
    userNameTv: {
        height: 40,
        fontSize: 25,
        color: 'black'
    },
    checkDetailsTv: {
        fontSize: 18,
        color: 'gray',
        textAlign: 'center'
    },

});